#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <arpa/inet.h>

#include "icar.h"
#include "icar_end_msg.h"
#include "icar_log.h"
#include "icar_utils.h"

struct icar_iovec *
end_response(int rsa,
		const char *number, struct endResponse *res)
{
	uint8_t data[10] = { 0 };
	int n = 0;
	uint16_t stmp;
	ICAR_HTONS(res->sequence);
	ICAR_HTONS(res->id);
	data[n++] = res->result;

	if (rsa == 0) {
		return icar_pkg_iovec(ICAR_END_RESPONSE, number, data, n);
	}
	return NULL;
}

struct icar_iovec *
end_heart_beat(int rsa, const char *number)
{
	if (rsa == 0)
		return icar_pkg_iovec(ICAR_END_HEARTBEAT, number, NULL, 0);
	return NULL;
}

struct icar_iovec *
end_end_register(int rsa, const char *number, struct endRegister *reg)
{
	return NULL;
}

struct icar_iovec *
end_unregister(int rsa, const char *number)
{
	if (rsa == ENCRYPT_NONE)
		return icar_pkg_iovec(ICAR_END_UNREGISTER, number, NULL, 0);

	return NULL;
}

struct icar_iovec *
end_auth(int rsa, const char *number, 
		const char *code, size_t size)
{
	if (rsa == ENCRYPT_NONE)
	{
		size_t len = size+1;
		int count = 0;
		uint8_t *data = icar_malloc(len);
		struct icar_iovec *iovec = NULL;
		if (!data)
			return NULL;
		memset(data, 0, len);
		if ((count = utf2Gbk(code, size+1, data, len)) > 0) {
			iovec = icar_pkg_iovec(ICAR_END_AUTHENTICATE, number, data, count);
		}
		free(data);
		return iovec;
	}

	return NULL;
}

struct icar_iovec *
end_update_notice(int rsa, const char *number, uint8_t type, uint8_t result)
{
	uint8_t data[8] = { 0 };
	data[0] = type & 0xff;
	data[1] = result & 0xff;

	if (rsa == ENCRYPT_NONE)
		return icar_pkg_iovec(ICAR_END_UPGRADE_NOTICE, number, data, 2);

	return NULL;

}

struct icar_iovec *
end_event_report(int rsa, const char *number, uint8_t id)
{
	if (rsa == ENCRYPT_NONE)
		return icar_pkg_iovec(ICAR_END_EVENT_REPORT, number, &id, 1);
	return NULL;
}

struct icar_iovec *
end_ask_response(int rsa, const char *number, uint16_t sequence, uint8_t id)
{
	struct icar_iovec *iovec = NULL;
	if (rsa == ENCRYPT_NONE)
	{
		uint8_t data[8] = { 0 };
		data[0] = sequence >> 8 & 0xff;
		data[1] = sequence & 0xff;
		data[2] = id;
		iovec = icar_pkg_iovec(ICAR_END_ASK_RESPONSE, number, data, 3);
	}

	return iovec;
}

struct icar_iovec *
end_infoMenu_cancel(int rsa, const char *number, uint8_t type, uint8_t flag)
{
	struct icar_iovec *iovec = NULL;

	if (rsa == ENCRYPT_NONE)
	{
		uint8_t data[8] = { 0 };
		data[0] = type & 0xff;
		data[1] = flag & 0xff;
		iovec = icar_pkg_iovec(ICAR_END_INFO_HELPMENU_CANCLE, number, data, 2);
	}

	return iovec;
}
